export interface GridDrawInfo {
  // 网格颜色
  color?: string;
  // 网格线条宽度
  lineWidth?: number;
  // 网格横向大小
  stepx?: number;
  // 网格纵向大小
  stepy?: number;
}

/**
 * 绘制网格
 * @param ctx 绘制上下文
 * @param info 网格绘制参数
 */
export function drawGrid(ctx: CanvasRenderingContext2D, info?: GridDrawInfo) {
  ctx.save();
  const canvas = ctx.canvas;
  ctx.strokeStyle = info?.color || "#bbb";
  ctx.lineWidth = info?.lineWidth || 0.5;
  const stepx = info?.stepx || 50;
  const stepy = info?.stepy || 50;
  // 在像素中点处绘制线，避免线条占两个像素
  const adjustPixel = 0.5;
  // 绘制横线
  for (let y = stepy; y < canvas.height; y += stepy) {
    ctx.moveTo(0, y + adjustPixel);
    ctx.lineTo(canvas.width, y + adjustPixel);
  }
  // 绘制纵线
  for (let x = stepx; x < canvas.width; x += stepx) {
    ctx.moveTo(x + adjustPixel, 0);
    ctx.lineTo(x + adjustPixel, canvas.height);
  }

  ctx.stroke();
  ctx.restore();
}
